package com.seari.client;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.seari.bean.ResultTrain;
import com.seari.client.kafka.KafkaReceiver;
import com.seari.controller.ATSWebsocketController;
import com.seari.pojo.ATSMessageBean;
import com.seari.service.TrainServiceImpl;

//数据对象快照功能，测试，待完善
@Component("ATSSnapshotClient")
public class ATSSnapshotClient extends BaseClient{
	protected static Logger logger = LoggerFactory.getLogger(ATSSnapshotClient.class);
	private static final long MAX_TIME_GAP = 10 * 60 * 1000; //最大信息有效间隔：10分钟

	@Override
	public void process() throws FileNotFoundException, IOException, ClassNotFoundException
	{
		checkAtsData();
	}
	
	private void checkAtsData()
	{
		Map<String, ConcurrentHashMap<String, ResultTrain>> sourceMap = TrainServiceImpl.trainMap;
		for (Entry<String, ConcurrentHashMap<String, ResultTrain>> parentEntry : sourceMap.entrySet())
		{
			logger.info("checkAtsData:before remove, line{},data size{}",parentEntry.getKey(),sourceMap.get(parentEntry.getKey()).size());
			Iterator<Entry<String, ResultTrain>> iterator = parentEntry.getValue().entrySet().iterator();
			while (iterator.hasNext())
			{
				Entry<String, ResultTrain> entry = iterator.next();
				ResultTrain resultTrain = entry.getValue();
				if(System.currentTimeMillis() - resultTrain.getUpdateTime() > MAX_TIME_GAP && resultTrain.getLineId() != null)
				{
					ATSMessageBean atsMessageBean = new ATSMessageBean();
					atsMessageBean.setType("remove");
					atsMessageBean.setData(resultTrain);
					try
					{
						ATSWebsocketController.broadCastInfo(KafkaReceiver.MAPPER.writeValueAsString(atsMessageBean));
						iterator.remove();
					} catch (JsonProcessingException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			logger.info("checkAtsData:after remove, line{},data size:{}",parentEntry.getKey(),sourceMap.get(parentEntry.getKey()).size());
		}
	}
}
